package com.huanghe.rabbitmq.topics;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Producer {

    public static void main(String[] args) {

        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        connectionFactory.setVirtualHost("/");

        Connection co = null;
        Channel channel = null;
        try {
            co = connectionFactory.newConnection("生产者");
            channel = co.createChannel();
//            String queueName = "queue7";
//            channel.queueDeclare(queueName, false, false, false, null);
            String msg = "hello topic message";
            String exchange = "topic-exchange";
            String routingKey = "com.order.test.xxx";
            String type = "direct";

            channel.basicPublish(exchange, routingKey, null, msg.getBytes());
            System.out.println("消息发送成功");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } finally {
            if (channel != null && channel.isOpen()) {
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
            }

            if (co != null && co.isOpen()) {
                try {
                    co.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
